import numpy as np
from math import sqrt
from collections import Counter

from sklearn.neighbors import KNeighborsClassifier

def kNN_classify(k, X_train, y_train, x):
    '''
        knn算法
    :param k:
    :param X_train:
    :param y_train:
    :param x:
    :return:
    '''
    assert 1 <= k <= X_train.shape[0], "k must be valid"
    assert X_train.shape[0] == y_train.shape[0], "this size of X_train must equal to the size of y_train"
    assert X_train.shape[1] == x.shape[0], "the feature number of x must be equal to X_train"

    distances = [sqrt(np.sum((item - x) ** 2)) for item in X_train]  # 求距离 同上上步
    nearest = np.argsort(distances)  # 排序,出来坐标
    topk_y = [y_train[i] for i in nearest[:k]]
    votes = Counter(topk_y)
    return votes.most_common(1)[0][0]
